/**
 * Html5 Stroage 相关 api
 */

export default {
    Stroage: function(isSession){
        try{
            return isSession ? window.sessionStorage : window.localStorage;
        }catch(e){
            return undefined;
        }
    },
    getType(value) {
        return Object.prototype.toString.call(value).match(/\s.*]$/ig)[0].replace(/(\s|])/g, '')
    },
    set: function(key, value, isSession){
        let Stroage = this.Stroage(isSession);
        if(Stroage && value !== undefined){
            const data = {data : value, type: this.getType(value)};
            if(data.type === 'Promise'){
                value.then( v =>{
                    data.data = v
                    data.type = '<Promise> resolve'
                }).catch(v => {
                    data.data = v
                    data.type = '<Promise> reject'
                }).finally(()=>{
                    Stroage.setItem(key, JSON.stringify(data))
                })
            }
            else Stroage.setItem(key, JSON.stringify(data))
        }
    },
    get: function(key, isSession){
        let Stroage = this.Stroage(isSession);
        if(Stroage && key){
            const data = JSON.parse(Stroage.getItem(key));
            if (data.type === '<Promise> resolve') {
                return Promise.resolve(data.data)
            } else if(data.type === '<Promise> reject') {
                return Promise.reject(data.data)
            }
            return data.data;
        }
        return undefined;
    },
    del: function(key, isSession){
        let Stroage = this.Stroage(isSession);
        if(Stroage && key){
            Stroage.removeItem(key);
        }
    },
    clear: function(isSession){
        let Stroage = this.Stroage(isSession);
        if(Stroage){
            Stroage.clear();
        }
    }
}